import {accountLogin, getCaptcha} from '@/services/api';
import {call, put, take} from "redux-saga/effects";
import {loginAction, loginSagaAction, logoutAction} from "./actionCreator";
import {GET_CAPTCHA, LOGIN, LOGOUT} from "./const";
import {reloadAuthorized} from "@/utils/Authorized";
import {getPageQuery} from "@/utils/utils";
import {history} from '@/utils/utils';
import {loginLoadingEndAction, loginLoadingStartAction} from "../loading/actionCreator";
import {removeToken, setToken, setUserInfo, storageClear} from "../../utils/authority";
import {SAVE_CURRENT_USER} from "../user/const";

function handleRedirect() {
  const urlParams = new URL(window.location.href);
  const params = getPageQuery();
  let {redirect} = params;
  if (redirect) {
    const redirectUrlParams = new URL(redirect);
    if (redirectUrlParams.origin === urlParams.origin) {
      redirect = redirect.substr(urlParams.origin.length);
      if (redirect.match(/^\/.*#/)) {
        redirect = redirect.substr(redirect.indexOf('#') + 1);
      }
    } else {
      window.location.href = redirect;
      return;
    }
  }
  history.replace(redirect || '/');
}

export function* login({payload}) {
  yield put(loginLoadingStartAction());

  try {
    const rsp = yield call(accountLogin, payload);
    if (rsp.status === 'OK') {
      yield put(loginAction({...rsp.data, status: rsp.status, statusText: rsp.statusText,}));
      reloadAuthorized();
      const data = rsp.data;
      yield put({type: SAVE_CURRENT_USER, payload: data.user});
      setUserInfo(data.user);
      setToken(data.token);
      handleRedirect();
      return true;
    }
  } catch (e) {
    console.log(e);
    if (e.response.status === 400) {
      yield put(loginAction({status: 'error', type: 'account'}));
    }
  } finally {
    yield put(loginLoadingEndAction());
  }
}

export function* getCaptchaSaga() {
  while (true) {
    const {payload} = yield take(GET_CAPTCHA);
    try {
      yield call(getCaptcha, payload);
    } catch (e) {
      console.log(e);
    }
  }
}

export function* logoutSaga() {
  yield put(logoutAction());
  reloadAuthorized();
  storageClear();
  history.push({
    pathname: '/user/login',
  });
}

export default function* loginFlow() {
  while (true) {
    const payload = yield take([LOGIN, LOGOUT]);
    if (payload.type === LOGIN) {
      // todo fix
      const isValid = yield call(login, payload);
    } else {
      yield call(logoutSaga);
    }
  }
}

